import 'package:ati_package/core/utils/ati_assets.dart';
import 'package:ati_package/core/utils/ati_color.dart';
import 'package:ati_package/core/utils/ati_font.dart';
import 'package:ati_package/pages/common/ati_scaffold.dart';
import 'package:ati_package/pages/find/mall/views/points_mall_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../widgets/user_bill_list_widget.dart';

class UserBillView extends StatefulWidget {
  const UserBillView({super.key});

  @override
  State<UserBillView> createState() => _UserBillViewState();
}

class _UserBillViewState extends State<UserBillView>
    with SingleTickerProviderStateMixin {
  TabController? tabController; // safer: allow null briefly
  final List<String> tabs = ['全部', '充值', '红包', '转账'];

  @override
  void initState() {
    super.initState();
    // 初始化 TabController（放在 initState 中正常创建）
    tabController = TabController(length: tabs.length, vsync: this);
  }

  @override
  void dispose() {
    tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AtiScaffold(
      extendBodyBehindAppBar: true,
      barBgColor: Colors.transparent,
      title: '账单明细',
      titleColor: AtiColor.textHLColor1,
      body: NestedScrollView(
        // ★ 关键参数：保证内部滚动与外部联动
        floatHeaderSlivers: false,
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(child: buildHeaderWidget()),
            SliverPersistentHeader(
              pinned: true,
              delegate: SliverTabBarDelegate(
                child: PreferredSize(
                  preferredSize: Size.fromHeight(50.r),
                  child: buildTabBar(),
                ),
              ),
            ),
            SliverToBoxAdapter(child: buildTimeWidget()),
          ];
        },
        // ★ 注意：每个 tab 内容要有唯一 Key
        body: TabBarView(
          controller: tabController,
          children: List.generate(tabs.length, (index) {
            return Builder(
              builder: (context) {
                return CustomScrollView(
                  // 为每个 tab 建立独立的滚动容器
                  key: PageStorageKey<String>(tabs[index]),
                  slivers: [
                    SliverPadding(
                      padding: EdgeInsets.all(16.r),
                      sliver: SliverGrid(
                        delegate: SliverChildBuilderDelegate(
                          (context, i) => UserBillListWidget(),
                          childCount: 20,
                        ),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 1,
                          crossAxisSpacing: 12.5.r,
                          mainAxisSpacing: 12.r,
                          childAspectRatio: 5.5,
                        ),
                      ),
                    ),
                  ],
                );
              },
            );
          }),
        ),
      ),
    );
  }

  //头部视图
  Widget buildHeaderWidget() {
    return Container(
      height: 200.r,
      padding: EdgeInsets.only(top: 12.5.w, left: 16.r, bottom: 12.5.r),
      decoration: BoxDecoration(color: Color(0xFF13BF78)),
      child: SafeArea(
        bottom: false,
        left: false,
        right: false,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [IncomeExpenseTab()],
        ),
      ),
    );
  }

  buildTimeWidget() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 2.5.h),
      color: const Color(0xFFF8FAFB), // 背景灰色
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 左侧：日期 + 下拉箭头
          InkWell(
            borderRadius: BorderRadius.circular(6.r),
            onTap: () {
              _showPicker();
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '2024-01',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
                SizedBox(width: 4.w),
                Icon(
                  Icons.keyboard_arrow_down_rounded,
                  size: 18.r,
                  color: Colors.black87,
                ),
              ],
            ),
          ),

          // 右侧：收入
          Text(
            '收入828282USDT',
            style: TextStyle(
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
              color: const Color(0xFF666666),
            ),
          ),
        ],
      ),
    );
  }

  void _showPicker() {
    Pickers.showDatePicker(
      context,
      mode: DateMode.YM, // ✅ 年月模式
      selectDate: PDuration(year: 2024, month: 12),
      minDate: PDuration(year: 2023, month: 1),
      maxDate: PDuration(year: 2025, month: 12),
      pickerStyle: PickerStyle(
        backgroundColor: Colors.white,
        headDecoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
        ),
        cancelButton: _buildButton("取消", Colors.grey.shade300, Colors.black87),
        commitButton: _buildButton("确定", const Color(0xFF4CAF50), Colors.white),
      ),

      onConfirm: (date) {
        setState(() {
          // _selected = "${date.year}-${date.month.toString().padLeft(2, '0')}";
        });
      },
    );
  }

  Widget _buildButton(String text, Color bg, Color textColor) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 45.r),
      padding: EdgeInsets.symmetric(horizontal: 37.5.r, vertical: 5.r),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: BorderRadius.circular(22.5),
      ),
      child: Text(text, style: TextStyle(color: textColor, fontSize: 16)),
    );
  }

  buildTabBar() {
    return Container(
      height: 90.r,
      margin: EdgeInsets.symmetric(horizontal: 16.r),
      child: TabBar(
        onTap: (value) {},
        controller: tabController,
        isScrollable: true,
        indicator: BoxDecoration(),
        tabAlignment: TabAlignment.start,
        dividerColor: Colors.transparent,
        indicatorColor: Colors.transparent, // 我们自己画 indicator
        splashFactory: NoSplash.splashFactory,
        overlayColor: WidgetStateProperty.all(Colors.transparent),
        labelPadding: EdgeInsets.only(
          right: 10.r,
          // top: 10.r,
        ), // ⚠️ 去掉 TabBar 自带 padding
        tabs: tabs.map((title) {
          final isSelected =
              tabController?.index == tabs.indexOf(title); // 当前是否选中

          return Tab(
            child: Container(
              padding: EdgeInsets.symmetric(
                horizontal: 17.5.r,
                vertical: 5.r,
              ), // ✅ 文字与边距
              decoration: BoxDecoration(
                color: isSelected ? AtiColor.primary : Colors.white,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Text(
                title,
                style: TextStyle(
                  fontSize: 14.r,
                  fontWeight: FontWeight.w600,
                  color: isSelected ? Colors.white : AtiColor.textColor1,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

//按键条
class IncomeExpenseTab extends StatefulWidget {
  const IncomeExpenseTab({super.key});

  @override
  State<IncomeExpenseTab> createState() => _IncomeExpenseTabState();
}

class _IncomeExpenseTabState extends State<IncomeExpenseTab> {
  int _selectedIndex = 0; // 0 收入，1 支出
  final List<String> _tabs = ['收入(USDT)', '支出(USDT)'];

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: Get.width - 32.r,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: List.generate(_tabs.length, (index) {
          final bool isSelected = _selectedIndex == index;
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedIndex = index;
              });
              if (_selectedIndex == 0) {
              } else {}
            },
            child: AnimatedContainer(
              width: (Get.width - 32.r - 22.5.r) / 2,
              duration: const Duration(milliseconds: 200),

              alignment: Alignment.center,

              padding: EdgeInsets.symmetric(horizontal: 20.w),
              decoration: BoxDecoration(
                image: isSelected
                    ? DecorationImage(
                        image: AssetImage(
                          AtiAssets.userBillBtnBg,
                          package: 'ati_package',
                        ),
                      )
                    : null,
                color: isSelected ? Colors.white : const Color(0xFF13BF78),
                borderRadius: BorderRadius.circular(8.r),
                border: isSelected
                    ? null
                    : Border.all(
                        color: isSelected ? Colors.grey.shade300 : Colors.white,
                        width: 1,
                      ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _tabs[index],
                    style: TextStyle(
                      color: isSelected ? AtiColor.textColor1 : Colors.white,
                      fontWeight: FontWeight.w500,
                      fontSize: AtiFont.font12,
                    ),
                  ),
                  Text(
                    '29166',
                    style: TextStyle(
                      color: isSelected ? Color(0xFF13BF78) : Colors.white,
                      fontWeight: FontWeight.w600,
                      fontSize: AtiFont.font20,
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }
}
